/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package session.stateful;

import entity.ProductEntity;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.Map;
import javax.ejb.Stateful;
import javax.ejb.LocalBean;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

/**
 *
 * @author edd
 */
@Stateful
@LocalBean
public class ProductSessionBean {

    // Add business logic below. (Right-click in editor and choose
    // "Insert Code > Add Business Method")
    @PersistenceContext
    EntityManager em;
    ProductEntity product;
    
    public ProductSessionBean() {
        
    }
    
    public void addProduct(String productName) {
        
        //product = new ProductEntity();
        em.persist(product);
    }
    
    public void deleteProduct(Long productId) throws Exception {
        
        product = em.find(ProductEntity.class, productId);
        if (product == null) 
            throw new Exception("Product does not exist.");
        else {
            em.remove(product);
        }
    }
    
    public void editProduct(Long productId, String productName) throws Exception {
        
        product = em.find(ProductEntity.class, productId);
        if (product == null) 
            throw new Exception("Product does not exist.");
        else {
            product.setProductName(productName);
            em.persist(product);
        }
    }
    
    public ArrayList<ProductEntity> viewProducts() {
        
        Query query = em.createQuery("SELECT p FROM Product p ORDER BY p.id asc");
        
        ArrayList listProducts = new ArrayList<ProductEntity>();
        
        for(Object o : query.getResultList()) {
            ProductEntity p = (ProductEntity) o;
            listProducts.add(p);
        }
        return listProducts;
    }
    
    public ArrayList<String> getProductNames() {
        
        Query query = em.createQuery("SELECT p.productName FROM Product p ORDER BY p.id asc");
        ArrayList productNames = new ArrayList<String>();
        
        for(Object o : query.getResultList()) {
            String p = (String) o;
            productNames.add(o);
        }
        return productNames;
    }
    
    public Map<String, Long> mapProductIdName() {
        
        Query query = em.createQuery("SELECT p FROM Product p ORDER By p.id asc");
        Map<String, Long> productIdName = new LinkedHashMap<String, Long>();
        
        for(Object o : query.getResultList()) {
            ProductEntity p = (ProductEntity) o;
            productIdName.put(p.getProductName(), p.getId());
        }
        return productIdName;
    }
    
}
